package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 
 * @date 2024/3/25 11:24
 */
@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    
    @Resource
    XcUserMapper xcUserMapper;
    
    @Resource
    ApplicationContext applicationContext;
    
    @Resource
    XcMenuMapper xcMenuMapper;

    /**
     * 
     * @param s username
     * @return
     * @throws UsernameNotFoundException
     */
    // 传入的请求认证参数就是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        
        // 讲传入的json转成AuthParamsDtoduix
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        // 认证类型，有password，wx....
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从spring中获取指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        
        // 统一调用execute方法完成认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        // 根据UserDetails对象生成令牌
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);
        
        return userPrincipal;

    }

    /**
     * 查询用户信息
     * @param user
     * @return
     */
    public UserDetails getUserPrincipal(XcUserExt user){
        String password = user.getPassword();
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities= {"p1"};
        // 根据用户id查询用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        if (xcMenus.size() > 0){
            ArrayList<String> permissions = new ArrayList<>();
            xcMenus.forEach(m -> {
                // 拿到了用户拥有的权限标识符
                permissions.add(m.getCode());
            });
            // 将Permission转成数组
            authorities = permissions.toArray(new String[0]);
        }
        System.out.println("authorities = " + authorities);
        user.setPassword(null);
        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        String userJson = JSON.toJSONString(user);
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
